package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"hello.domain.p"}) //设置Repository所在位置
public class PrimaryConfig {

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        Map<String, String> map = jpaProperties.getHibernateProperties(dataSource);
        return map;
    }

    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
        Map<String, String> map = getVendorProperties(primaryDataSource);

        EntityManagerFactoryBuilder.Builder builder1 = builder.dataSource(primaryDataSource);
        builder1 = builder1.properties(map);

        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = builder
                .dataSource(primaryDataSource)
                .properties(map)
                .packages("hello.domain.p") //设置实体类所在位置
                .persistenceUnit("primaryPersistenceUnit")
                .build();

        return entityManagerFactoryBean;
    }

    @Primary
    @Bean
    public EntityManager entityManagerPrimary(EntityManagerFactoryBuilder builder) {
        EntityManagerFactory entityManagerFactory = entityManagerFactoryPrimary(builder).getObject();
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        return entityManager;
    }

    @Primary
    @Bean
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }
}
